import 'package:flutter/material.dart';
import '../../dropdown_menu_picker.dart';

typedef MenuOpenCallback = void Function(bool isOpen, int currentIndex);

/// headerWidget控件布局外部自定义
typedef HeaderBuilder = Widget Function(DropDownHeaderItem item, bool isShow);

class DropDownHeader extends StatefulWidget {
  /// 标记控件元素引用
  final GlobalKey stackKey;

  /// 整个控件的高度 默认70
  final double height;

  /// child子控件的高度 默认49
  final double innerHeight;

  /// 标记当前控件的索引
  final int currentIndex;

  /// child控件的边框宽，默认为1
  final double borderWidth;

  /// child控件的边框宽、色值，默认为Color(0xFFeeede6)
  final Color borderColor;

  /// child控件的Padding - EdgeInsets.symmetric(horizontal: 15.0, vertical: 10.0),
  final EdgeInsetsGeometry innerPadding;

  /// 连接器
  final DropdownMenuController controller;

  /// 子控件的builder方法集合
  final List<HeaderBuilder> childBuilders;

  /// 子控件的信息配置集合
  final List<DropDownHeaderItem> itemList;

  /// 点击header时回调方法，返回显示/隐藏，当前控件索引值
  final MenuOpenCallback onTapCallback;

  // final Color color;
  // final TextStyle style;
  // final TextStyle dropDownStyle;
  // final double iconSize;
  // final Color iconColor;
  // final iconDropDownColor;
  // final Color selectedTitleColor;
  // final Color selectedBorderColor;
  // final double dividerHeight;
  // final Color dividerColor;
  // final OnItemTap onItemTap;
  // final DropDownHeaderItem item;
  // final HeaderBuilder headerBuilder;

  DropDownHeader(
      {Key key,
      this.childBuilders,
      @required this.itemList,
      @required this.controller,
      @required this.stackKey,
      this.height = 70,
      this.innerHeight = 40,
      this.innerPadding =
          const EdgeInsets.symmetric(horizontal: 15.0, vertical: 10.0),
      this.borderWidth = 1,
      this.borderColor = const Color(0xFFeeede6),
      this.onTapCallback,
      this.currentIndex = 0
      // @required this.items,
      // this.headerBuilder,
      // this.selectedBorderColor = const Color(0xFFE0E0E0),
      // this.selectedTitleColor = const Color(0xFF757575),
      // this.style = const TextStyle(color: Color(0xFF666666), fontSize: 13),
      // this.dropDownStyle,
      // this.iconColor = const Color(0xFFafada7),
      // this.iconDropDownColor,
      // this.iconSize = 20,
      // this.dividerColor = const Color(0xFFeeede6),
      // this.dividerHeight = 20,
      // this.onItemTap,
      // this.color = Colors.white,
      })
      : super(key: key);

  @override
  State<StatefulWidget> createState() => _DropDownHeaderState();
}

class _DropDownHeaderState extends State<DropDownHeader>
    with SingleTickerProviderStateMixin {
  GlobalKey _keyDropDownHeader = GlobalKey();
  bool _isShowDropDownItemWidget = false;
  // double _screenWidth;
  // int _menuCount;
  // TextStyle _dropDownStyle;
  // Color _iconDropDownColor;
  // Color _selectedBorderColor;
  // Color _selectedTitleColor;

  @override
  void initState() {
    super.initState();
    // _selectedBorderColor = widget.selectedBorderColor;
    // _selectedTitleColor = widget.selectedTitleColor;
    widget.controller.addListener(() {
      if (mounted) {
        setState(() {});
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // _dropDownStyle = widget.dropDownStyle ??
    //     TextStyle(color: Theme.of(context).primaryColor, fontSize: 13);
    // _iconDropDownColor =
    //     widget.iconDropDownColor ?? Theme.of(context).primaryColor;

    // MediaQueryData mediaQuery = MediaQuery.of(context);
    // _screenWidth = mediaQuery.size.width;
    // _menuCount = widget.items.length;
    // var gridView = GridView.count(
    //     crossAxisCount: _menuCount,
    //     physics: NeverScrollableScrollPhysics(),
    //     childAspectRatio: (_screenWidth / _menuCount) / widget.height,
    //     children: widget.items.map<Widget>((item) {
    //       return _menuItemWidget(item);
    //     }).toList());

    return Container(
      key: _keyDropDownHeader,
      height: widget.height,
      decoration: BoxDecoration(
          border:
              Border.all(color: widget.borderColor, width: widget.borderWidth)),
      child: Container(
          height: widget.innerHeight,
          padding: widget.innerPadding,
          // child: gridView,
          // 整个外部包装了一层Container控件
          child: Row(
            children: _translateChildren(widget.childBuilders, widget.itemList),
          )),
    );
  }

  List<Widget> _translateChildren(
      List<HeaderBuilder> childBuilders, List<DropDownHeaderItem> itemList) {
    List<Widget> tempList = [];
    if (itemList.length != childBuilders.length) {
      return [
        Container(
          color: Colors.green,
          child: Text('控件和数据源个数不匹配'),
        )
      ];
    }
    // 以数据源为维度，布局UI
    for (var i = 0; i < itemList.length; i++) {
      tempList.add(Expanded(
        child: _menuItemWidget(childBuilders[i], itemList[i]),
        flex: itemList[i].flexRatio,
      ));
    }
    return tempList;
  }

  Widget _menuItemWidget(HeaderBuilder childBuilder, DropDownHeaderItem item) {
    int index = widget.itemList.indexOf(item);
    int menuIndex = widget.controller.menuIndex;
    _isShowDropDownItemWidget = index == menuIndex && widget.controller.isShow;
    return GestureDetector(
      onTap: () {
        final RenderBox overlay =
            widget.stackKey.currentContext.findRenderObject();
        final RenderBox dropDownItemRenderBox =
            _keyDropDownHeader.currentContext.findRenderObject();
        var position =
            dropDownItemRenderBox.localToGlobal(Offset.zero, ancestor: overlay);
        var size = dropDownItemRenderBox.size;
        widget.controller.dropDownHeaderHeight = size.height + position.dy;

        if (index == menuIndex) {
          if (widget.controller.isShow) {
            widget.controller.hide();
            widget.onTapCallback(false, widget.currentIndex);
          } else {
            widget.controller.show(index);
            widget.onTapCallback(true, widget.currentIndex);
          }
        } else {
          if (widget.controller.isShow) {
            widget.controller.hide(isShowHideAnimation: false);
            widget.onTapCallback(false, widget.currentIndex);
            // widget.controller.hide();
          }
          // else {
          // 点击当前header并且关闭之前正在展示的选项框
          widget.onTapCallback(true, widget.currentIndex);
          widget.controller.show(index);
          // }
          // widget.controller.show(index);

        }
        // if (widget.onItemTap != null) {
        //   // widget.onItemTap(index);
        //   widget.onItemTap();
        // }
        setState(() {});
      },
      // child: UnconstrainedBox(
      child: childBuilder(item, _isShowDropDownItemWidget),
      // Container(child: Text(item.title),width: 80,color: _isShowDropDownItemWidget ? Colors.red : Colors.green,),
      // widget.headerBuilder != null
      //     ? widget.headerBuilder(item, _isShowDropDownItemWidget)
      //     : Container(
      //         // padding: EdgeInsets.symmetric(horizontal: 15.0),
      //         // height: 50.0,
      //         decoration: BoxDecoration(
      //             borderRadius: BorderRadius.circular(5.0),
      //             border: Border.all(
      //                 color: _selectedBorderColor,
      //                 // ThemeUtils.getThemeColor(
      //                 //     context: context,
      //                 //     brightnessColor: Colors.grey[300],
      //                 //     darkColor: Colors.white),
      //                 width: 1.0,
      //                 style: BorderStyle.solid)),
      //         // color: widget.color,
      //         // color: Colors.red,
      //         // padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 35.0),
      //         child: Row(
      //           mainAxisAlignment: MainAxisAlignment.center,
      //           children: <Widget>[
      //             Expanded(
      //                 child: Row(
      //               mainAxisAlignment: MainAxisAlignment.center,
      //               children: <Widget>[
      //                 // Flexible(
      //                 //     child: Text(
      //                 //   item.title,
      //                 //   maxLines: 1,
      //                 //   overflow: TextOverflow.ellipsis,
      //                 //   style: _isShowDropDownItemWidget
      //                 //       ? _dropDownStyle
      //                 //       : widget.style.merge(item.style),
      //                 // )),
      //                 SizedBox(
      //                   width: 15.0,
      //                 ),
      //                 Text(item.title ?? '',
      //                     style: TextStyle(
      //                       fontSize: 14,
      //                       color: _selectedTitleColor,
      //                       // ThemeUtils.getThemeColor(
      //                       //     context: context,
      //                       //     brightnessColor: Colors.grey[600],
      //                       //     darkColor: Colors.white)
      //                     )),
      //                 Spacer(),
      //                 Icon(
      //                   !_isShowDropDownItemWidget
      //                       ? item.iconData ?? Icons.arrow_drop_down
      //                       : item.iconData ?? Icons.arrow_drop_up,
      //                   color: _isShowDropDownItemWidget
      //                       ? _iconDropDownColor
      //                       : item?.style?.color ?? widget.iconColor,
      //                   size: item.iconSize ?? widget.iconSize,
      //                 ),
      //                 SizedBox(
      //                   width: 15.0,
      //                 ),
      //               ],
      //             )),
      //             // index == widget.items.length - 1
      //             //     ? Container()
      //             //     : Container(
      //             //         height: widget.dividerHeight,
      //             //         decoration: BoxDecoration(
      //             //             border: Border(
      //             //                 right: BorderSide(
      //             //                     color: widget.dividerColor, width: 1))),
      //             //       )
      //           ],
      //         ),
      //       ),
      // ),
    );
  }
}
